package com.baor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baor.dao.*;
import com.baor.domain.*;
import com.baor.domain.conf.ProxyConf;
import com.baor.enums.FuncEnum;
import com.baor.service.ProxyOrderService;
import com.baor.utils.AjaxResult;
import com.baor.utils.DateUtil;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.baor.utils.DateUtil.now;

@Service
public class ProxyOrderServiceImpl implements ProxyOrderService {

    @Autowired
    private ProxyOrderDao proxyOrderDao;
    @Autowired
    private ProxyDao proxyDao;
    @Autowired
    private ProxyLevelDao proxyLevelDao;
    @Autowired
    private VipDao vipDao;
    @Autowired
    private DistributionRecordDao distributionRecordDao;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private ProxyConfDao proxyConfDao;
    @Autowired
    private BackDao backDao;
    @Autowired
    private MoneyDao moneyDao;
    @Autowired
    private OrderDao orderDao;

    /*
    * 插入订单调用
    * */
    @Override
    @Transactional
    public AjaxResult<?> insertProxyOrder(OrderVo orderVo) {
        Integer superiorId = Integer.valueOf(vipDao.selectById(orderVo.getUserId()).getUserSuperior());
        ProxyVo proxyVo = getProxyVo(superiorId);
        if(proxyVo == null){
            return AjaxResult.error("上级用户不是代理商");
        }
        ProxyOrderVo proxyOrderVo = new ProxyOrderVo();
        proxyOrderVo.setOrderId(String.valueOf(orderVo.getOrderId()));
        proxyOrderVo.setOrderCode(orderVo.getOrderCode());
        proxyOrderVo.setCreateTime(orderVo.getCreateTime());
        proxyOrderVo.setGoodsId(orderVo.getGoodsId());
        proxyOrderVo.setSinglePrice(orderVo.getPriceValue());
        proxyOrderVo.setOrderNum(Math.toIntExact(orderVo.getOrderGoodsNum()));
        proxyOrderVo.setBuyUser(orderVo.getUserId());
        proxyOrderVo.setProxyUser(String.valueOf(superiorId));
        proxyOrderVo.setProxyLevel(proxyVo.getProxyLevelId());
        proxyOrderVo.setSiteId(orderVo.getSiteId());
        proxyOrderVo.setAllCommission(BigDecimal.ZERO);

        //查看退款状态
//        BackVo backVo = backDao.selectOne(new LambdaQueryWrapper<BackVo>().eq(BackVo::getOrderId, orderVo.getOrderId()));
//        if(backVo == null){
//            proxyOrderVo.setBackStatus(null);
//        }else{
//            proxyOrderVo.setBackStatus(backVo.getPack_status());
//        }
        int row = proxyOrderDao.insert(proxyOrderVo);
        if (row > 0){
            return AjaxResult.success();
        }
        return AjaxResult.error("该订单不是代理订单");
    }

    //查询上级用户是不是代理商
    public ProxyVo getProxyVo(int superiorId){
        //判断上级用户是否是代理商
        LambdaQueryWrapper<ProxyVo> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(ProxyVo::getUserId, superiorId);
        ProxyVo proxyVo = proxyDao.selectOne(lqw1);
        if(proxyVo == null){
            return null;
        }
        return proxyVo;
    }

    /*
    * 更新订单状态调用
    * */
    @Override
    @Transactional
    public AjaxResult<?> updateCommission(int orderId){
        //根据orderId查询订单
        OrderVo orderVo = orderDao.selectOne(new LambdaQueryWrapper<OrderVo>().eq(OrderVo::getOrderId, orderId));
        if(Integer.parseInt(orderVo.getOrderStatusId()) != 12){
            return AjaxResult.error("订单状态不正确，无法更新佣金");
        }
        //查看自己是否为代理商
        ProxyVo proxyVo = getProxyVo(Integer.parseInt(orderVo.getUserId()));
        if(proxyVo == null){
            //查看上级是否为代理商
            Integer superiorId = Integer.valueOf(vipDao.selectById(orderVo.getUserId()).getUserSuperior());
            proxyVo = getProxyVo(superiorId);
            if(proxyVo == null){
                return AjaxResult.error("代理不存在，无法更新佣金");
            }
        }
        //查看当前站点代理设置是否开启
        ProxyConf proxyConf = proxyConfDao.selectOne(new LambdaQueryWrapper<ProxyConf>().eq(ProxyConf::getSiteId, orderVo.getSiteId()));

        int row = 0;
        BigDecimal res = new BigDecimal(0);
        if(Integer.parseInt(proxyConf.getConfOpen()) == 1) {
            //查询代理商折扣
            ProxyLevelVo proxyLevelVo = proxyLevelDao.selectById(proxyVo.getProxyLevelId());
            BigDecimal discount = proxyLevelVo.getLevelDiscount();
            BigDecimal dis = new BigDecimal(10).subtract(discount);
            //计算代理佣金
            res = res.add(orderVo.getPriceValue().multiply(dis).divide(new BigDecimal(10)));
            //更新代理佣金
            ProxyOrderVo proxyOrderVo = new ProxyOrderVo();
            proxyOrderVo.setOrderId(String.valueOf(orderVo.getOrderId()));
            proxyOrderVo.setAllCommission(res);
            LambdaQueryWrapper<ProxyOrderVo> lqw = new LambdaQueryWrapper<>();
            lqw.eq(ProxyOrderVo::getOrderId, orderId);
            row = proxyOrderDao.update(proxyOrderVo, lqw);
        }
        if (row > 0) {
            //更新代理商代理佣金
            ProxyVo proxyVo1 = new ProxyVo();
            proxyVo1.setProxyId(proxyVo.getProxyId());
            proxyVo1.setProxyTotalMoney(proxyVo.getProxyTotalMoney().add(res));
            proxyDao.updateById(proxyVo1);

            UserVo userVo = vipDao.selectOne(new LambdaQueryWrapper<UserVo>().eq(UserVo::getUserId, proxyVo.getUserId()));
            //插入佣金变动记录
            MoneyVo money = getMoneyVo(userVo, res);
            moneyDao.insert(money);
            //更新user表的数据
            UserVo userVo1 = updateMoney(userVo, res);
            vipDao.updateById(userVo1);
            return AjaxResult.success();
        }else{
            return AjaxResult.error("更新佣金失败");
        }
    }

    //佣金变动记录
    public MoneyVo getMoneyVo(UserVo userVo,BigDecimal disMoney ){
        MoneyVo money = new MoneyVo();
        money.setUserName(userVo.getUserName());
        money.setUserTel(userVo.getUserTel());
        money.setCreateTime(now());
        money.setUserId(String.valueOf(userVo.getUserId()));
        money.setAccountType("余额");
        money.setSiteId(userVo.getSiteId());
        money.setMoneySourceId("代理返现");
        money.setMoneyChange(disMoney);
        money.setMoneyFinal(userVo.getUserCanuseMoney().add(disMoney));
        money.setMoneyStatus("0");
        return money;
    }

    //更新user表的钱数据
    public UserVo updateMoney(UserVo userVo,BigDecimal disMoney){
        userVo.setUserCantBe(userVo.getUserCantBe().add(disMoney));
        userVo.setUserCanuseMoney(userVo.getUserCanuseMoney().add(disMoney));
        userVo.setUserDistributionMoney(userVo.getUserDistributionMoney().add(disMoney));
        userVo.setUserTotalMoney(userVo.getUserTotalMoney().add(disMoney));
        userVo.setUserTotalDistribution(userVo.getUserTotalDistribution().add(disMoney));
        return userVo;
    }

    public BigDecimal getDisMoney(OrderVo orderVo, ProxyVo proxyVo){
        //查看当前站点代理设置是否开启
        ProxyConf proxyConf = proxyConfDao.selectOne(new LambdaQueryWrapper<ProxyConf>().eq(ProxyConf::getSiteId, orderVo.getSiteId()));
        //查询代理商折扣
        if(Integer.parseInt(proxyConf.getConfOpen()) == 1){
            ProxyLevelVo proxyLevelVo = proxyLevelDao.selectById(proxyVo.getProxyLevelId());
            BigDecimal discount = proxyLevelVo.getLevelDiscount();
            BigDecimal dis = new BigDecimal(10).subtract(discount);
            BigDecimal res = orderVo.getPriceValue().multiply(dis).divide(new BigDecimal(10));
            return res;
        }
        return new BigDecimal(0);
    }

    @Override
    public AjaxResult<?> orderList(Map<String, Object> params) {
        Map<String, Object> map = new HashMap<>();
        if(params.get("pageIndex") == null || "".equals(params.get("pageIndex"))){
            params.put("pageIndex",0);
            params.put("pageSize",5);
        }else{
            params.put("pageIndex",Integer.parseInt(params.get("pageSize").toString()) * (Integer.parseInt(params.get("pageIndex").toString()) - 1));
        }
        List<ProxyOrderVo> list = proxyOrderDao.orderList(params);
        map.put("list", list);
        map.put("pageCount", proxyOrderDao.pageCount(params));
        return AjaxResult.success(map);
    }

    public MPJLambdaWrapper<ProxyOrderVo> getMPJ(){
        MPJLambdaWrapper<ProxyOrderVo> mpj = new MPJLambdaWrapper<>();
        mpj.selectAll(ProxyOrderVo.class)
                .selectAs(GoodsVo::getGoodsName, ProxyOrderVo::getGoodsId)
                .selectAs(ProxyLevelVo::getLevelName, ProxyOrderVo::getProxyLevel)
                .selectFunc(FuncEnum.IF_SUMMARY,ProxyOrderVo::getSummaryStatus)
                .selectAs(UserVo::getUserName, ProxyOrderVo::getBuyUser)
                .leftJoin(GoodsVo.class, GoodsVo::getGoodsId, ProxyOrderVo::getGoodsId)
                .leftJoin(ProxyLevelVo.class, ProxyLevelVo::getProxysLevelId, ProxyOrderVo::getProxyLevel)
                .leftJoin(UserVo.class, UserVo::getUserId, ProxyOrderVo::getBuyUser);

        return mpj;
    }

    private Page<ProxyOrderVo> getPage(Map<String,Object> map){
        if ( map.get("pageIndex") == null || "".equals(map.get("pageIndex")) )
            map.put("pageIndex",1);
        if ( map.get("pageSize") == null || "".equals(map.get("pageSize")) )
            map.put("pageSize",5);
        Long pageIndex = Long.valueOf(map.get("pageIndex").toString());
        Long pageSize = Long.valueOf(map.get("pageSize").toString());
        Page<ProxyOrderVo> page = new Page<>(pageIndex,pageSize);
        return page;
    }




}
